% 一维扩散方程

% 已知量
alpha = 1/(pi^2);
dt = 0.0025;
dx = 0.025;
t0 = 0;
tmax = 1;
x0 = -1;
xmax = 1;
nt = (tmax - t0)/dt;
nx = (xmax - x0)/dx;
belta = alpha*dt/(dx^2);
x = zeros(nx+1);
un=zeros(nt+1,nx+1);
ue=[];
% 初始条件
for j=1:nx+1
    x(j)=x0+(j-1)*dx;
    un(1,j)=-sin(pi*x(j));
    ue(j)=-exp(-tmax)*sin(pi*x(j)); % 精确解
end
un(1,1) = 0;
un(1,nx+1) = 0;


% FTCS
for j=2:nt+1
    for k=2:nx
        un(j,k)=un(j-1,k)+belta*(un(j-1,k+1)-2*un(j-1,k)+un(j-1,k-1));
    end
    un(j,1)=0.0;    % x=-1时的边界条件
    un(j,nx+1)=0.0; % x=1 时的边界条件
end
subplot(1,2,1);
plot(-1:dx:1,un(nt+1,:),"Color",'r','LineStyle','--')
hold on
plot(-1:dx:1,ue,"Color",'b')
hold off
subplot(1,2,2)
rms= compute_l2norm(un(nt+1,:),ue);
plot(-1:dx:1,rms)
function rms=compute_l2norm (un,ue)
        rms=sqrt((ue-un).^2);
end


